import 'dart:async';
import 'dart:ffi';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_libserialport/flutter_libserialport.dart';
import 'package:logger/logger.dart';
import 'package:custom_pop_up_menu/custom_pop_up_menu.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:ponydata_desk/model/position_model.dart';
import 'package:ponydata_desk/pages/channel_cell.dart';
import 'package:ponydata_desk/pages/channel_item.dart';
import 'package:ponydata_desk/pages/tem_legend.dart';
import 'package:ponydata_desk/pages/wafer_section.dart';
import 'package:ponydata_desk/utils/Command.dart';
import 'package:ponydata_desk/utils/utils.dart';

import '../res/positons30.dart';
import 'line_chart.dart';

class ChartPage extends StatefulWidget {
  const ChartPage({super.key});

  @override
  State<ChartPage> createState() => _ChartPageState();
}

class _ChartPageState extends State<ChartPage> {

  TextStyle subTitleStyle = TextStyle(
      color: Color(0xFF333333), fontSize: 18, fontWeight: FontWeight.w500);

  TextStyle subBodyTitleStyle = TextStyle(
      color: Color(0xFF017FF4), fontSize: 16, fontWeight: FontWeight.w500);


  String deviceType = "测试设备";

  TextEditingController _macController =  TextEditingController();

  // 最后操作时间
  int lastSendEvent=DateTime.now().millisecondsSinceEpoch;

  // 命令组
  List<String> commands = [];
  // 当前命令
  String _command = "";

  String _resBuffer = "";

  // 温度原始数据
  List<String> _original = [];

  // 温度原始数据
  List<List<double>> _temDatas = [];

  List<ChannelModel> _channelModels = [];
  
  //当前的选中的通道
  ChannelModel? _currentChannelModel;
  
  // 命令执行失败 是否重试
  bool _repeat = false;
  // 命令执行失败 重试次数
  var _repeatCount = 10;
  // 命令执行失败次数
  var _failCount = 0;

  // 0 未操作  1 开始采样 2 结束采样 3 数据读取
  var _state = 0;

  var _tostTxt = "命令执行成功！";

  String portName="";

  var availablePorts = [];

  var baudRates = [38400,115200,];

  var stopBitList = [1,2,];

  var bitList = [8,7,6,5];

  var paritys = [1,];

  // 奇偶校验
  int parity =0;
  int baudRate = 0;
  int bits = 0;
  int stopBits = 0;

  SerialPort? _port ;

  bool isOpen = false;

  bool _running = false;

  Timer? _timer;

  String convertToAscii(String input) {
    List<int> asciiValues = input.runes.map((rune) => rune.toUnsigned(16)).toList();
    // 将整数列表转换为带前导零补足两位的十六进制字符串形式
    String asciiHexString = asciiValues.map((value) => value.toRadixString(16).padLeft(2, '0')).join('');
    return asciiHexString;
  }

  String generateCommand(String input) {
    return "0A"+convertToAscii(input)+"0D";
  }

  @override
  void initState() {
    super.initState();

    refashConfig();
    clearDatas();
    Future.delayed(Duration.zero, () {
      initPorts();
    });
  }

  void refashCommandText(){
    if(mounted){
      setState(() {
        _command="";
        _macController.text="";
      });
    }
  }
  void refashConfig(){


    if(mounted){
      setState(() {
        if(availablePorts.isNotEmpty){
          portName = availablePorts.first;
          // portName = "COM3";

        }
        parity = paritys.first;
        stopBits = stopBitList.first;
        baudRate =  baudRates.first;
        bits = bitList.first;
      });
    }
  }

  void clearDatas(){
    List<ChannelModel> pos = [];
    pos1.forEach((element) {
      ChannelModel channelModel = ChannelModel.fromJson(element);
      pos.add(channelModel);
    });
    if(mounted){
      setState(() {
        _original = [];
        _temDatas = [];
        _channelModels = pos;
        _currentChannelModel=null;
      });
    }

  }

  void initPorts() {
    if(isOpen){
      BotToast.showText(text: "请先关闭串口连接");
      return;
    }
    if(_port!=null){
      _port!.close();
      _port = null;
    }

    setState(() => availablePorts = SerialPort.availablePorts);
    print(availablePorts);
    if(availablePorts.isNotEmpty){
      availablePorts.forEach((element) {
        if(element=="COM3"){
          if(mounted){
            setState(() {
              portName = "COM3";
              // portName = availablePorts.first;
            });
          }
        }
      });
    }
    if(portName=="COM3") {
      BotToast.showText(text: "串口信息获取完成");
    }else{
      showPortErrorDialog();
    }
  }

  void startTimer(){
    if(_timer!=null){
      _timer!.cancel();
    }
    _running = true;
    var seconds = 0;
    Timer.periodic(Duration(milliseconds: 10), (timer) {
      _timer = timer;
      if(_running==false){
        timer.cancel();
        return;
      }
      if(seconds >= 300 ){
        timer.cancel(); // 取消重复计时
        BotToast.closeAllLoading();
        BotToast.showText(text: "命令执行超时");
        return;
      }
      seconds++;// 秒数+1
    });
  }


  Future<void> showPortErrorDialog() async {

    String userPrivateProtocol = "未找到串口信息，是否重试？";

    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return new AlertDialog(
          title: new Text('温馨提示'),
          content: Container(
            height: 30,
            child: SingleChildScrollView(
              child: RichText(
                //文字居中
                textAlign: TextAlign.center,
                //文字区域
                text: TextSpan(
                  text: userPrivateProtocol,
                  style:Theme.of(context).textTheme.bodyText2,

                ),
              ),
            ),
          ),
          actions: <Widget>[
            TextButton(onPressed: (){
              Navigator.of(context).pop();
            }, child: new Text('取消')),
            TextButton(onPressed: (){

              Navigator.of(context).pop();
              initPorts();
            }, child: new Text('重试',style: TextStyle(
                color: Theme.of(context).errorColor
            ),))
          ],
        );
      },
    ).then((val) {
      print(val);
    });
  }

  void openPort(){
    if(portName==null||portName.length==0){
      BotToast.showText(text: "请先选择串口");
      return;
    }

    if(!checkEventFrequency()){
      return;
    }

    SerialPort port = SerialPort(portName);
    port.config.baudRate = baudRate;
    port.config.bits = bits;
    port.config.parity = parity;
    port.config.stopBits = stopBits;
    _readData(port);
  }
  bool checkEventFrequency(){

    int current =DateTime.now().millisecondsSinceEpoch;

    if(current-lastSendEvent<1000){
      BotToast.showText(text: "操作不能太频繁");
      return false;
    }
    lastSendEvent = current;
    return true;
  }

  void closeSerial(){

    if(!checkEventFrequency()){
      return;
    }

    if(_port!=null){
      bool isClose = _port!.close();
      if(isClose){
        BotToast.showText(text: "串口关闭成功");
        _port=null;
      }else{
        BotToast.showText(text: "串口关闭失败");
      }
      if(mounted){
        setState(() {
          isOpen = !isClose;
        });
      }
    }
  }

  void _readData(SerialPort port) async {
    // 读数据
    final reader = SerialPortReader(port, timeout: 10);

    if( port.openReadWrite()){
      if(mounted){
        setState(() {
          isOpen = true;
        });
      }
      BotToast.showText(text: "串口打开成功");
      _port =port;

    }else{
      if(mounted){
        setState(() {
          isOpen = false;
        });
      }
      BotToast.showText(text: "串口打开失败");
    }

    reader.stream.listen((data) {
      _running=false;
      // String hexString = data.map((byte) =>  byte.toRadixString(16).padLeft(2, '0')).join('').toUpperCase();

      String asciiString = data.map((charCode) {
        if (charCode == 10) return '<LF>';
        if (charCode == 13) return '<CR>';
        return String.fromCharCode(charCode);
      }).join('');

      // 保存完整结果
      if(_resBuffer.length==0 && asciiString.startsWith("<LF>")){

        _resBuffer = asciiString;

        if(_resBuffer.endsWith("<CR><LF>")){
          print("结束--${_resBuffer}");
          checkResult(_resBuffer.substring(4,_resBuffer.length-8));
          _resBuffer="";
        }

      }else{
        _resBuffer = _resBuffer+asciiString;
        if(_resBuffer.endsWith("<CR><LF>")){
          print("结束111--${_resBuffer}");
          checkResult(_resBuffer.substring(4,_resBuffer.length-8));
          _resBuffer="";
        }
      }
    });
    //执行接下来的操作
  }

  // 检查结果是否有要继续执行的命令
  void checkResult(String resContent){

    bool isACK = _command == CommandStr.START_UPLOAD_ACK?true:false;

    if((resContent.length>2 && isACK==false) || (_command == CommandStr.START_UPLOAD_ACK && resContent== "R0004")){

      // 读取长度生成读取命令
      if( _command == CommandStr.READ_BUFFER_lENGTH){
        // 获取数据长度
        var length = Utils.hexToInt(resContent.substring(1,5));

        print("READ_BUFFER_lENGTH --${resContent}====${resContent.substring(1,5)}===${length}");

        for(int i=0;i<length;i++){
          commands.add(CommandStr.START_UPLOAD_DATA);
          commands.add(CommandStr.START_UPLOAD_ACK);
          commands.add(CommandStr.READ_BUFFER_PAGE1);
          commands.add(CommandStr.READ_BUFFER_PAGE2);
          commands.add(CommandStr.READ_BUFFER_PAGE3);
          commands.add(CommandStr.READ_BUFFER_PAGE4);
        }
      }

      if(_command==CommandStr.READ_BUFFER_PAGE1|| _command==CommandStr.READ_BUFFER_PAGE2|| _command==CommandStr.READ_BUFFER_PAGE3|| _command==CommandStr.READ_BUFFER_PAGE4){

        _original.add(resContent.substring(1));
      }

      if(commands.length>0){
         // 删除执行完成的
         commands.removeAt(0);
      }
      if(commands.length>0){

        _command = commands.first;
        Future.delayed(Duration(milliseconds: 100), () {
          senData();
        });
      }else{
        BotToast.closeAllLoading();
        BotToast.showText(text: _tostTxt);
        print(_original);
        getTemDataList(_original);
      }
      if(_repeat){
        _failCount = 0;
      }
    }else{
      if(_repeat){
        if(_failCount<_repeatCount){
          Future.delayed(Duration(milliseconds: 1000), () {
            senData();
          });
          _failCount++;
        }else{
          _failCount = 0;

          BotToast.closeAllLoading();
          BotToast.showText(text: "命令执行失败");
        }
      }else{

        BotToast.closeAllLoading();
        BotToast.showText(text: "命令执行失败");
      }
    }
  }

  getTemDataList(List datas){

    datas.forEach((element) {
      splitIntoChunks(element,4);
    });

    //赋值 channelmodel
    print(_temDatas);
    if(_temDatas.length!=32){
      return;
    }
    List<ChannelModel> models = _channelModels;
    int index = 0;
    for(int i=0;i<_temDatas.length;i++){
      if(i==5 || i==17){
        continue;
      }

      ChannelModel model = models[index];

      if(i==0){
        model.select = true;
      }
      model.tems = _temDatas[i];
      model.value =_temDatas[i].last;

      var max = 0.0;
      var min = 1000.0;
      var sum = 0.0;
      var count = 0;
      _temDatas[i].forEach((element) {
        if(element>max){
          max = element;
        }
        if(element<min){
          min = element;
        }
        sum += element;
        count++;
      });
      model.max = max;
      model.min = min;
      model.range = double.parse((max-min).toStringAsFixed(1));
      model.avg = double.parse((sum/count).toStringAsFixed(1));
      print(model.tems!.length);
      print(model.max);

      index++;
    }
    if(mounted){
      setState(() {
        _channelModels = models;
      });
    }

    _currentChannelModel = _channelModels.first;

  }

 void splitIntoChunks(String source, int chunkSize) {

    if (source.isEmpty || chunkSize <= 0) return ;

    List<String> chunks = [];
    int index = 0;
    for (int i = 0; i < source.length; i += chunkSize) {

      var data = source.substring(i, i + chunkSize > source.length ? source.length : i + chunkSize);
      var tem = double.parse((Utils.hexToInt(data)/128).toStringAsFixed(1));

      if(_temDatas.length>index){
        var device = _temDatas[index];
        device.add(tem);
      }else{
        List<double> device = [tem];
        _temDatas.add(device);
      }
      index++;
    }
  }

  void senData() async {

    if(isOpen==false || _port==null){
      BotToast.closeAllLoading();
      BotToast.showText(text: "请打开串口");
      return ;
    }

    if (_command == null || _command.length==0) {
      BotToast.closeAllLoading();
      BotToast.showText(text: "请输入命令");
      return;
    }
    startTimer();
    Uint8List command = Utils.hexStringToUint8List(_command);
    int state = _port!.write(command);
    print('发送数据state-${command}---${_command}');
  }

  // 开始数据采集
  void startCollection(){
    _tostTxt = "已开始采样！";
    commands = [CommandStr.RFID_POWER_ON,CommandStr.READ_EPC,CommandStr.CLEAR_DATA,CommandStr.START_TEM];
    _command = commands.first;
    _repeat = false;
    clearDatas();
    senData();
  }

  // 停止数据采集
  void stopCollection(){
    _tostTxt = "已结束采样！";
    commands = [CommandStr.TSOP_TEM];
    _command = commands.first;
    _repeat = false;
    senData();
  }

  // 开始读取数据
  void readDatas(){
    BotToast.showLoading();
    _tostTxt = "已完成读取数据！";
    commands = [CommandStr.READ_BUFFER_lENGTH];
    _command = commands.first;
    _repeat =true;
    _original = [];
    senData();
  }

  Widget itemBuilder(BuildContext context, int index) {
    // return SetPage();
    ChannelModel channelModel = _channelModels[index];
    return ChannelCell(selectRespond: (ChannelModel pos){
      if(mounted){
        setState(() {
          if(_currentChannelModel!=null){
            _currentChannelModel!.select=false;
          }
          channelModel.select=!channelModel.select!;
          if(channelModel.select!){
            _currentChannelModel = channelModel;

          }
        });
      }
    }, channelModel: channelModel,);
  }

  List<Widget> getTemBlocks() {
    List<Widget> items = [];
    _channelModels.forEach((channelModel) {
      double x =  (channelModel.x! + 75.0)/150*420-23;
      double y =  (channelModel.y! + 75.0)/150*420-23+10;
      items.add(Positioned(left: x, top: y, child: Container(child: ChannelItem(channelModel: channelModel,),)));
    });

    return items;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: LayoutBuilder(builder: (context, constraints) {
        // print(constraints.maxWidth);
        // print(constraints.maxHeight);

        // 假设我们想要的宽高比是16:9
        double aspectRatio = 16 / 9;
        double width = constraints.maxWidth;

        double mainWidth = width * 0.6;

        double height = width / aspectRatio;

        // 如果可用的垂直空间不足以满足我们的需求，我们调整大小
        if (height > constraints.maxHeight) {
          height = constraints.maxHeight;
          width = height * aspectRatio;
        }

        return Container(
          // color: Colors.redAccent,
          height: height,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              //头部
              Container(
                padding: EdgeInsets.fromLTRB(38, 0, 38, 0),
                height: 64,
                color: Colors.white,
                child: Row(
                  children: [
                    GestureDetector(
                        onTap: (){},
                        child: Container(
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text("配置",
                                  style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 14,
                                      fontWeight: FontWeight.w400)),
                              Icon(Icons.keyboard_arrow_down)
                            ],
                          ),
                        )),

                    Expanded(child: Container()),
                    Container(width: 160,child:Icon(Icons.import_export,color:isOpen?Colors.greenAccent:Theme.of(context).colorScheme.error),),

                    Container(
                      margin: EdgeInsets.only(right: 56),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                              width: 40,
                              height: 40,
                              margin: EdgeInsets.only(right: 8),
                              decoration: BoxDecoration(
                                  color: Colors.black,
                                  border: new Border.all(
                                      color: Theme.of(context).dividerColor,
                                      width: 0.5), // 边色与边宽度
                                  borderRadius: BorderRadius.circular(20))),
                          Text("用户名",
                              style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 14,
                                  fontWeight: FontWeight.w400)),
                        ],
                      ),
                    ),
                    Container(
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.only(right: 8),
                            child: Icon(Icons.login_outlined),
                          ),
                          Text("推出登录",
                              style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 14,
                                  fontWeight: FontWeight.w400)),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              // 身体
              Expanded(
                  child: Container(
                color: Color(0xFFF0F2F5),
                padding: EdgeInsets.fromLTRB(16,16,16,16),
                child: Container(
                  color: Colors.white,
                  child: Row(
                    children: [
                      //圆盘
                      Column(mainAxisAlignment: MainAxisAlignment.start,children: [
                        Expanded(
                          child: Container(
                            width: mainWidth,
                            child: Row(
                              children: [
                                Expanded(
                                    child: Container(
                                        padding:
                                            EdgeInsets.fromLTRB(24, 10, 24, 0),
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              "设备类型：${deviceType}",
                                              style: TextStyle(
                                                  color: Color(0xD9666666),
                                                  fontSize: 14),
                                            ),
                                           Container(
                                             // height:  mainWidth - 240 - 102,
                                              // color: Colors.lightBlueAccent,
                                              child: Column(
                                                children: [
                                                  Text(
                                                    "90°",
                                                    style: TextStyle(
                                                        color:
                                                            Color(0xFFACC7DA),
                                                        fontSize: 12),
                                                  ),
                                                  Container(
                                                    // color: Colors.redAccent,
                                                    // height:
                                                    //     mainWidth - 240 - 102,
                                                    child: Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .center,
                                                      crossAxisAlignment: CrossAxisAlignment.center,
                                                      children: [
                                                        Text(
                                                          "180°",
                                                          style: TextStyle(
                                                              color: Color(
                                                                  0xFFACC7DA),
                                                              fontSize: 12),
                                                        ),
                                                        Expanded(
                                                          child: Container(
                                                            margin: EdgeInsets.
                                                                only(left: 4,right: 4),
                                                            // color: Colors.orange,
                                                            width: height - 270,
                                                            height: height - 270 ,
                                                              decoration: BoxDecoration(
                                                                image: DecorationImage(
                                                                  image: AssetImage(
                                                                    "lib/res/images/card.png",
                                                                  ), // 背景图的网络链接
                                                                  fit: BoxFit.cover, // 背景图适应容器大小
                                                                ),
                                                              ),
                                                            child:Stack(children: getTemBlocks(),)
                                                          ),
                                                        ),
                                                        Text(
                                                          "0°",
                                                          style: TextStyle(
                                                              color: Color(
                                                                  0xFFACC7DA),
                                                              fontSize: 12),
                                                        ),
                                                      ],
                                                    ),
                                                  ),
                                                  Text(
                                                    "270°",
                                                    style: TextStyle(
                                                        color:
                                                            Color(0xFFACC7DA),
                                                        fontSize: 12),
                                                  ),
                                                  //色块
                                                  Container(
                                                    margin: EdgeInsets.only(
                                                        top: 20,left: 80,right: 80),
                                                    child: TemLegend(),
                                                  )
                                                ],
                                              ), )
                                          ],
                                        ))),
                                // 列表
                                Container(
                                  padding: EdgeInsets.only(top: 50, right: 10),
                                  width: 240,
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      Container(
                                        width: 240,
                                        height: 80,
                                        color: Color(0xFFF0F0F0),
                                        child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceAround,
                                          children: [
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.spaceAround,
                                              children: [
                                                Text(
                                                  "最高",
                                                  style: subTitleStyle,
                                                ),
                                                Container(
                                                  height: 20,
                                                  width: 1,
                                                  color: Color(0xFFCDCDCD),
                                                ),
                                                Text(
                                                  "最低",
                                                  style: subTitleStyle,
                                                ),
                                                Container(
                                                  height: 20,
                                                  width: 1,
                                                  color: Color(0xFFCDCDCD),
                                                ),
                                                Text(
                                                  "差值",
                                                  style: subTitleStyle,
                                                ),
                                                Container(
                                                  height: 20,
                                                  width: 1,
                                                  color: Color(0xFFCDCDCD),
                                                ),
                                                Text(
                                                  "平均",
                                                  style: subTitleStyle,
                                                ),
                                              ],
                                            ),
                                            Container(
                                              height: 1,
                                              color: Color(0xFFCDCDCD),
                                            ),
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.spaceAround,
                                              children: [
                                                Text(
                                                  "${_currentChannelModel==null|| _currentChannelModel!.max!<=0?"--":_currentChannelModel!.max!}",
                                                  style: subBodyTitleStyle,
                                                ),
                                                Container(
                                                  height: 20,
                                                  width: 1,
                                                  color: Color(0xFFCDCDCD),
                                                ),
                                                Text(
                                                  "${_currentChannelModel==null|| _currentChannelModel!.min!<=0?"--":_currentChannelModel!.min!}",
                                                  style: subBodyTitleStyle,
                                                ),
                                                Container(
                                                  height: 20,
                                                  width: 1,
                                                  color: Color(0xFFCDCDCD),
                                                ),
                                                Text(
                                                  "${_currentChannelModel==null|| _currentChannelModel!.range!<=0?"--":_currentChannelModel!.range!}",
                                                  style: subBodyTitleStyle,
                                                ),
                                                Container(
                                                  height: 20,
                                                  width: 1,
                                                  color: Color(0xFFCDCDCD),
                                                ),
                                                Text(
                                                  "${_currentChannelModel==null|| _currentChannelModel!.avg!<=0?"--":_currentChannelModel!.avg!}",
                                                  style: subBodyTitleStyle,
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ),
                                      Expanded(
                                          child: Container(
                                        margin: EdgeInsets.only(top: 30,bottom: 20),
                                        width: 200,
                                        child: ListView.builder(
                                            itemCount:_channelModels!=null? _channelModels.length:0,
                                            itemBuilder: itemBuilder),
                                      ))
                                    ],
                                  ),
                                )
                              ],
                            ),
                          ),
                        ),
                        Container(
                          width: mainWidth,
                          height: 1,
                          color: Color(0xFFCDCDCD),
                        ),
                        // 操作
                        Container(
                          height: 60,
                          margin: EdgeInsets.only(right: 240),
                          padding: EdgeInsets.all(12),
                          child: Row(children: [
                            ElevatedButton(onPressed: startCollection, style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Color(0xFF2FC25B))), child:Center(child: Text("开始采样",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 14),),),),
                            SizedBox(width: 32,),
                            ElevatedButton(onPressed: stopCollection, style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Color(0xFFF04864))), child:Center(child: Text("停止采样",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 14),),),),
                            SizedBox(width: 32,),
                            ElevatedButton(onPressed:readDatas, style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Color(0xFF1890FF))), child:Center(child: Text("读取数据",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 14),),),)
                          ],),
                        )
                      ]),

                      Container(
                        width: 16,
                        color: Color(0xFFF0F2F5),
                      ),
                      // 图表
                      Expanded(
                        child: Container(
                          padding: EdgeInsets.fromLTRB(10, 70, 10, 100),
                          // color: Colors.redAccent,
                          child:Column(crossAxisAlignment: CrossAxisAlignment.start,children: [
                            Text(
                            "温度数据分析",
                            style: TextStyle(
                                color: Colors.black,
                                fontSize: 18),),
                            SizedBox(height: 20,),
                            Expanded(child:LineChartSection(channelModel: _currentChannelModel,))
                            ,
                          ],)
                        ),
                      )
                    ],
                  ),
                ),
              ))
            ],
          ),
        );
       }),
      floatingActionButton: FloatingActionButton(
        child:Text(isOpen?"关闭":"连接",style: TextStyle(fontWeight: FontWeight.w600,color: !isOpen?Colors.greenAccent:Theme.of(context).colorScheme.error),),
        onPressed:  isOpen?closeSerial:openPort,
      ),
    );
  }
}



